<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2016-10-18
 * Time: 15:40
 */

namespace app\mobileweb\controller;

use app\src\jsqdb\logic\DevListLogic;
use app\src\post\logic\PostLogic;
use app\src\post\model\Post;
use app\src\user\action\LoginAction;
use app\src\base\helper\ConfigHelper;
use app\src\base\helper\ValidateHelper;
use app\src\system\logic\SecurityCodeLogic;
use app\src\system\model\SecurityCode;
use app\src\user\action\DeleteAction;
use app\src\user\action\RegisterAction;
use app\src\user\action\UpdateAction;
use app\src\user\enum\RegFromEnum;
use app\src\user\facade\DefaultUserFacade;
use app\src\user\logic\UcenterMemberLogic;
use app\src\user\model\UcenterMember;
use app\src\base\utils\BoyeService;
use think\Session;
use think\Controller;

/**
 *
 * Index作为登录接口
 *
 */
class Login extends Webview
{
    public function _initialize()
    {
        $this->needValid =false;  //不需要验证用户密码
        parent::_initialize();
    }

    /**
     * 自动登录接口 - 目前主要用于刷新
     * @author hebidu <email:346551990@qq.com>
     */
    public function autoLogin(){
        $uid = $this->_post('uid','',lang('id_need'));
        $auto_login_code = $this->_post('auto_login_code','',lang('auto_login_code_need'));
        $result = (new DefaultUserFacade())->autoLogin($uid,$auto_login_code);
        $this->exitWhenError($result,true);
    }

    /**
     * 更新用户信息接口
     * @author hebidu <email:346551990@qq.com>
     */
    public function update(){
        $this->checkVersion("100");

        $uid = $this->_post('uid','',lang('lack_parameter',['param'=>'uid']));
        $nickname = $this->_post('nickname','');
        $sex = $this->_post('sex','');
        $sign = $this->_post('sign','');//个性签名
        $email = $this->_post('email','');//邮箱

        $loc_country = $this->_post('loc_country','');
        $loc_area = $this->_post('loc_area','');

        $weixin = $this->_post('weixin','');
        $job_title = $this->_post('job_title','');//职位
        $company = $this->_post('company','');//公司

        //1. member_config 表字段更新
        $member_config = [];
        if(!empty($job_title)){
            $member_config['job_title'] = $job_title;
        }
        if(!empty($company)){
            $member_config['company'] = $company;
        }
        if(!empty($weixin)){
            $member_config['weixin'] = $weixin;
        }

        if(!empty($loc_country)){
            $member_config['loc_country'] = $loc_country;
            $member_config['loc_area'] = $loc_area;
        }

        //1. common_member 表字段更新
        $user_entity = [];
        if(!empty($nickname)){
            $user_entity['nickname'] = $nickname;
        }
        if(strlen($sex) > 0){
            $sex = intval($sex);
            if($sex == 0 || $sex == 1){
                $user_entity['sex'] = $sex;
            }
        }
        if(!empty($sign)){
            $user_entity['sign'] = $sign;
        }

        $ucenter_entity = [];
        if(!empty($email)){
            $ucenter_entity['email'] = $email;
        }

        $action = new UpdateAction();

        $entity = array(
            'ucenter_entity'=>$ucenter_entity,
            'user_entity'=>$user_entity,
            'member_config'=>$member_config,
            'uid'=>$uid
        );

        $result = $action->update($entity);

        $this->exitWhenError($result,true);
    }

    /**
     * 找回密码-通过旧密码的形式
     * @author hebidu <email:346551990@qq.com>
     */
    public function updatePwdByOldPwd(){

        $this->checkVersion("100");

        $uid = $this->_post('uid','', lang('uid_need'));
        $password = $this->_post('password','', lang('password_need'));
        $new_password = $this->_post('new_password','', lang('password_need'));

        $salt = ConfigHelper::getPasswordSalt();
        $crypt_password = think_ucenter_md5($password,$salt);

        $logic = new UcenterMemberLogic();
        $result = $logic->getInfo(['id'=>$uid]);
        if(!$result['status'] || empty($result['info'])){
            $this->apiReturnErr(lang('invalid_parameter',['param'=>'uid']));
        }

        $userinfo = $result['info'];
        if($userinfo['password'] != $crypt_password){
            $this->apiReturnErr(lang('err_incorrect_password'));
        }


        //2. 调用修改密码
        $action = new UpdateAction();
        $result = $action->updatePwd(['id'=>$uid,'password'=>$crypt_password],$new_password);

        $this->exitWhenError($result,true);
    }

    /**
     * 找回密码-通过手机号+手机验证码的形式
     * @author hebidu <email:346551990@qq.com>
     */
    public function updatePwd(){
        if(IS_POST){
            $country = $this->_post('country','+86');
            $mobile = $this->_post('mobile','');
            $code = $this->_post('code','');
            $password = $this->_post('password','');
            $device_token = $this->_post('device_token','');
            $device_type  = 'pc';
            $data = array(
                "country" => $country,
                "mobile" => $mobile,
                'code'=>$code,
                'password'=>$password
            );
            $t= array(
                'api_ver'  => 101,
                'notify_id'=> time(),
                'alg'      => 'md5',
                'device_token'=>$device_token,
                'device_type'=>$device_type,
                'type'	   => 'BY_User_updatePwd'
            );

            $data = array_merge($t, $data);
            $service=new Boyeservice();
            $fanhui=$service->callRemote('',$data,false);
            if(!$fanhui['status']) $this->apiReturnErr($fanhui['info']);

            $this->success('更新成功请重新登录','login/login');

        }else{

            return $this->fetch();

        }
    }

    /**
     * 通过5分钟时效的授权码来修改密码
     * @author hebidu <email:346551990@qq.com>
     */
    public function updatePwdWithAuthCode(){

        $uid = $this->_post('uid','',lang('id_need'));
        $encryptPwd = $this->_post('password','',lang('password_need'));
        $auth_code = $this->_post('auth_code','',lang('invalid_parameter',['param'=>'auth_code']));
        $new_pwd  = $this->_post('new_pwd','',lang('invalid_parameter',['param'=>'new_pwd']));

        $logic  = new UcenterMemberLogic();

        $result = $logic->getInfo(['id'=>$uid,'password'=>$encryptPwd]);

        if(!$result['status']){
            $this->apiReturnErr($result['info']);
        }

        $userinfo = $result['info'];

        if(!is_array($userinfo)){
            $this->apiReturnErr(lang('err_modified'));
        }

        if($auth_code != "itboye" && empty(think_ucenter_decrypt($auth_code,$uid))){
            $this->apiReturnErr(lang('err_auth_code'));
        }

        $action = new UpdateAction();
        $result = $action->updatePwd(['id'=>$uid],$new_pwd);

        $this->exitWhenError($result,true);
    }

    /**
     * 登录接口
     * @author hebidu <email:346551990@qq.com>
     */
    public function loginByCode(){
        if(IS_POST){
            $country = $this->_post('country','+86');
            $mobile = $this->_post('mobile','');
            $code = $this->_post('code','');
            $device_token = $this->_post('device_token','');
            $device_type  = 'pc';
            $data = array(
                "country" => $country,
                          "mobile" => $mobile,
                          'code'=>$code,
            );
            $t= array(
                'api_ver'  => 101,
                'notify_id'=> time(),
                'alg'      => 'md5',
                'device_token'=>$device_token,
                'device_type'=>$device_type,
                'type'	   => 'BY_User_loginByCode'
            );

            $data = array_merge($t, $data);
            $service=new Boyeservice();
            $fanhui=$service->callRemote('',$data,false);


            $user=$fanhui['info'];
            if($fanhui['status']){
                session('userinfo',$user);
            }
            if(!$fanhui['status']) $this->apiReturnErr($fanhui['info']);
            $this->redirect('index/index','3');

        }else{

            return $this->fetch();

        }
    }

    /**
     * 登录接口
     * @author hebidu <email:346551990@qq.com>
     */
    public function login(){
        if(IS_POST){
        $country = $this->_post('country','+86');
        $username = $this->_post('username','');
        $password = $this->_post('password','');
        $device_token = $this->_post('device_token','');
        $device_type  = 'pc';
            $data = array("country" => $country,
                          "username" => $username,
                          'password'=>$password,
                          'device_token'=>$device_type,
                          'device_type'=>$device_type,
            );
            $t= array(
                'api_ver'  => 102,
                'notify_id'=> time(),
                'alg'      => 'md5',
                'type'	   => 'BY_User_login'
            );
            $data = array_merge($t, $data);
            $service=new Boyeservice('by571846d03009e1','964561983083ac622f03389051f112e5');
            $fanhui=$service->callRemote('',$data,false);
            $user=$fanhui['info'];
            if($fanhui['status']){
                session('userinfo',$user);
            }
            if(!$fanhui['status']) $this->apiReturnErr($fanhui['info']);

            $this->redirect('index/index','3');

        }else{

            return $this->fetch();
        }
    }

    /**
     * 注册接口
     * @author hebidu <email:346551990@qq.com>
     */
    public function register(){
        if(IS_POST){
            $country = $this->_post('country','+86');
            $username = $this->_post('username','');
            $code = $this->_post('code','');
            $device_token = $this->_post('device_token','');
            $device_type  = 'pc';
            $password=$this->_post('password','');
            $data = array("country" => $country,
                          "username" => $username,
                          'password'=>$password,
                          'code'=>$code,
            );
            $t= array(
                'api_ver'  => 101,
                'notify_id'=> time(),
                'alg'      => 'md5',
                'device_token'=>$device_token,
                'device_type'=>$device_type,
                'type'	   => 'BY_User_register'
            );
            $data = array_merge($t, $data);
            $service=new Boyeservice();
            $fanhui=$service->callRemote('',$data,false);
            var_dump($fanhui);

        }else{
            return $this->fetch();
        }
    }

    /**
     * 删除
     * @author hebidu <email:346551990@qq.com>
     */
    public function delete(){
        $this->checkVersion("100");
        $mobile = $this->_post('mobile','',lang('mobile_need'));

        $logic = new DeleteAction();
        $result = $logic->delete($mobile);
        $this->exitWhenError($result,true);
    }


    //发送验证码
    public function send(){
        $country=$this->_post('country','+86');
        $mobile=$this->_post('mobile','');
        $code_type=$this->_post('code_type','');

        $data = array(
            "country" => $country,
                      'mobile' => $mobile,
                      'code_type'=>$code_type,
        );
        $t= array(
            'api_ver'  => 101,
            'notify_id'=> time(),
            'alg'      => 'md5',
            'device_type'=>'pc',
            'type'	   => 'By_SecurityCode_send'
        );
        $data = array_merge($t, $data);

        $service=new Boyeservice();
        $fanhui=$service->callRemote('',$data,false);
        return $fanhui['info'];
    }


}